#!/bin/bash

# Exit on error, unbound variables
set -eu

bindiff_release=8
binexport_release=12

function log() {
  syslog -s -l error "BinDiff postinstall: $1"
}

log "Starting"

log "Environment:"
env | while read line; do log "  ${line}"; done

# If the application directory does not exist, exit
APP_DIR=/Applications/BinDiff
cd "${APP_DIR}" || exit 2
CONFIG_FILE="/Library/Application Support/BinDiff/bindiff.json"

LOGGED_IN_UID=$(id -u "${USER}")
log "LOGGED_IN_UID: ${LOGGED_IN_UID}"

# If the /usr/local/bin directory does not exist, create it.
mkdir -p /usr/local/bin

BUNDLE_DIR="${APP_DIR}/BinDiff.app/Contents"
for exe in \
  bindiff \
  binexport2dump
do
  log "Symlink ${BUNDLE_DIR}/MacOS/bin/${exe} -> /usr/local/bin/"
  chmod +x "${BUNDLE_DIR}/MacOS/bin/${exe}"
  ln -sf "${BUNDLE_DIR}/MacOS/bin/${exe}" /usr/local/bin/
done

BINDIFF_CONFIG_SETUP="${BUNDLE_DIR}/MacOS/bin/bindiff_config_setup"

# Setup install location in config file. Note that we leave "ui.java_binary"
# unset, so that the native launcher stub is invoked.
log "Adjusting config file for UI directory: ${BUNDLE_DIR}/MacOS"
"${BINDIFF_CONFIG_SETUP}" --config "${CONFIG_FILE}" \
  "directory=${BUNDLE_DIR}/MacOS" \
  "ui.java_binary="

# Pre-populate the IDA Pro installation path, looking for the latest version.
IDA_DIR=$(mdfind kMDItemCFBundleIdentifier==com.hexrays.ida64 | \
  sort -r | head -n 1)/Contents/MacOS
if [ -d "${IDA_DIR}" ]; then
  log "Adjusting config file for IDA Pro found at: ${IDA_DIR}"
  "${BINDIFF_CONFIG_SETUP}" --config "${CONFIG_FILE}" \
    "ida.directory=${IDA_DIR}"
else
  log "No installation of IDA Pro found, skipping config change"
fi

# Create symlinks for the IDA Pro plugins. These get recreated on each log in,
# if they don't exist.
# Note the double escape below, first bash, then sed.
LOAD_CMD="\"${BINDIFF_CONFIG_SETUP}\" --per_user"
log "Adjusting launch agent file: ${LOAD_CMD}"
sed -i "" "s,LOAD_CMD,${LOAD_CMD}," \
  /Library/LaunchAgents/com.google.security.zynamics.bindiff.plist

if [ -z "${COMMAND_LINE_INSTALL+x}" ]; then
  log "Running launchctl as current user for final config"
  /bin/launchctl asuser "${LOGGED_IN_UID}" \
    /bin/launchctl unload \
    -F /Library/LaunchAgents/com.google.security.zynamics.bindiff.plist
  /bin/launchctl asuser "${LOGGED_IN_UID}" \
    /bin/launchctl load \
    -F /Library/LaunchAgents/com.google.security.zynamics.bindiff.plist
else
  log "Command line install, skipping launchctl"
fi

log "Finished"
